<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/14
 * Time: 14:36
 */
namespace Library\db;

class Dao{
    protected $values=[];

    public $suffix='';

    protected $table;

    protected $field;
    protected $where;
    protected $order;
    protected $limit;
    protected $connection;
    private $_compExp = array(
        'neq' => '!=',
        'gte' => '>=',
        'lte' => '<=',
        'notlike' => 'NOT LIKE',
        'gt' => '>',
        'lt' => '<',
        'eq' => '=',
        'like' => 'LIKE'
    );

    public function __construct()
    {
        $this->connection=Db::factory('PdoDriver');

    }
    public function __set($name , $value){
        $this->values[$name] = $value;
    }

    public function __get($name){
        if(isset($this->values[$name])){
            return $this->values[$name];
        }
        else{
            return null;
        }
    }
    //组合field字段
    function field($field){
        $this->field=$field;
        return $this;
    }
    function where($where){
        $this->where=" WHERE ".$where;
        return $this;
    }
    //组合where数组条件
    function whereArray($where){
        if(empty($where)) {
            return $this;
        }
        if(is_string($where)) {
             $this->where=' WHERE ' . $where;
             return $this;
        }elseif(is_array($where)) {
            $str = ' WHERE ';
            $arrLen = count($where);
            $count = 0;
            foreach($where as $key => $val) {
                if(preg_match('/^lt|lte|gt|gte|eq|neq|like|notlike$/i',$val[0])) {
                    $command = $this->_parseCompExp($val[0]);
                    $str .= (' ' . $key . ' ' . $command . ' ' . $val[1]);
                } elseif('in' === strtolower($val[0])) {
                    if(is_array($val[1])) {
                        $str .= (' ( ' . $key . ' IN ' . implode(',',$val[1]) . ')');
                    } else {
                        $str .= (' ( ' . $key . ' IN ' . $val[1] . ' ) ');
                    }
                } elseif('between' === strtolower($val[0])) {
                    $data = explode(',',$val[1]);
                    $str .= (' ' . $key . ' BETWEEN ' . $data[0] . ' AND ' . $data[1] . ' ');
                } else {}
                if($count + 1 < $arrLen) {
                    if(isset($val[2])) {
                        $str .= (' ' . $val[2] . ' ');
                    } else {
                        $str .= ' AND ';
                    }
                }
                $count ++;
            }
            $this->where=$str;
            return $this;
        } else {}
    }
    //组合order排序条件
    function order($order){
        $this->order="order by ".$order;
        return $this;
    }
    //组合limit限制条数
    function limit($limit){
        $this->limit="limit ".$limit;
        return $this;
    }
    //组合和执行select语句
    function select($all=""){
        if ($all) {
            $sql="select {$all} from {$this->suffix}{$this->table} {$this->where} order by id";
        }else{
            $sql="select {$this->field} from {$this->suffix}{$this->table} {$this->where} {$this->order} {$this->limit}";
        }

        $value_array=$this->connection->get_array($sql);
        if (count($value_array)>=1){
            foreach($value_array as $key => $value){
                $this->values[$key] = $value;
            }
        }
        return $this->values;
    }
    //组合和执行insert语句
    function insert($post){ //数据库插入操作,接收数组
        foreach ($post as $key => $value) {
            $keys[]=$key;
            $vals[]="'".$value."'";
        }
        $keyStr=join(",",$keys);
        $valStr=join(",",$vals);
        $sql="insert into {$this->suffix}{$this->table} ($keyStr) values({$valStr})";
        $this->id = $this->connection->insert_get_id($sql);
    }
    //组合和执行delect语句
    function delect(){
        $sql="DELETE from {$this->suffix}{$this->table} {$this->where}";
        return $this->connection->execute($sql);
    }
    //组合和执行updata语句
    function update($post){
        foreach ($post as $key => $value) {
            $sets[]="`{$key}`='" . $this->connection->clean($value) . "'";
        }
        $setStr=join(",",$sets);
        $sql="update {$this->suffix}{$this->table} set {$setStr} {$this->where} ";
        return $this->connection->execute($sql);
    }
    //从表中取一行数据
    function find(){
        if ($this->order) {
            $sql="select {$this->field} from {$this->suffix}{$this->table} {$this->where} {$this->order} limit 1";
        }else{
            $sql="select {$this->field} from {$this->suffix}{$this->table} {$this->where} {$this->order} limit 1";
        }
        $value_array=$this->connection->get_array($sql);

        if(!isset($value_array[0])){
            $value_array[0] = array();
        }

        foreach($value_array[0] as $key => $value){
            $this->values[$key] = $value;
        }
        return $this->values;
    }
    //获取总行数
    function count(){
        $sql="select count(*) from {$this->suffix}{$this->table} {$this->where}";
        $arr=mysqli_fetch_array($this->connection->execute($sql),1);
        return $arr['count(*)'];
    }
    private function _parseCompExp($exp) {
        if(is_string($exp)) {
            return str_replace(array_keys($this->_compExp),array_values($this->_compExp),$exp);
        }elseif(is_array($exp)) {
            $tmpArr = array();
            foreach($exp as $val) {
                $tmpArr[] = str_replace(array_keys($this->_compExp),array_values($this->_compExp),$val);
            }
            return $tmpArr;
        } else {
            //不能解析，直接返回
            return $exp;
        }
    }

}